
#include <string.h>

#include "get_question_and_answer.h"

const unsigned int max_line     = 1024 *2;
const char question_token[]     = "<q>";
const char question_token_end[] = "</q>";
const char answer_token[]       = "<ans>";
const char answer_token_end[]   = "</ans>";


// Internal function prototypes
int get_next_question(struct z_quiz* quiz, char* psz_question, 
    unsigned short n_question_size);

int get_next_answer(struct z_quiz* quiz, char* psz_answer, unsigned short n_answer_size);

int get_next_item(struct z_quiz* quiz, char* psz_item_return, unsigned short n_item_return_size, 
        const char* psz_token, const char* psz_token_end);

// External functions
int quiz_open(struct z_quiz* quiz, const char* psz_quiz_name) 
{
    if((quiz->fp_in = fopen(psz_quiz_name, "r")) == NULL) {
        return (1);
    }
    
    return (0);
}

int quiz_get_question_and_answer(struct z_quiz* quiz, char* psz_question, 
    unsigned short n_question_size, char* psz_answer, unsigned short n_answer_size)
{
    if ((get_next_question(quiz, psz_question, n_question_size) == 0) &&
            (get_next_answer(quiz, psz_answer, n_answer_size) == 0)) {
        return(0);
    }
 
    return (1);
}

int quiz_close(struct z_quiz* quiz)
{
    fclose(quiz->fp_in);
    return (0);
}
 
// Internal functions 
int get_next_question(struct z_quiz* quiz, char* psz_question, 
    unsigned short n_question_size)
{
    return (get_next_item(quiz, psz_question, n_question_size, question_token, question_token_end));
}

int get_next_answer(struct z_quiz* quiz, char* psz_answer, unsigned short n_answer_size)
{
    return (get_next_item(quiz, psz_answer, n_answer_size, answer_token, answer_token_end));
}

int get_next_item(struct z_quiz* quiz, char* psz_item_return, unsigned short n_item_return_size, 
        const char* psz_token, const char* psz_token_end)
{
    char keep_looking_for_item = 1;
    char sz_text_in[max_line];
    char* p_item_start;
    char* p_item_end;    

    while (keep_looking_for_item == 1)
    {
        if (fgets(sz_text_in, max_line, quiz->fp_in) == NULL)
            return(1);

        p_item_start = strstr(sz_text_in, psz_token);            
        if (p_item_start != NULL)
        {
            keep_looking_for_item = 0;
            p_item_start = p_item_start + strlen(psz_token);
            p_item_end = strstr(p_item_start, psz_token_end);
            if (p_item_end == NULL)
                return(1);
            
            strcpy(p_item_end, "");
            strncpy(psz_item_return, p_item_start, n_item_return_size);
        }    
    }

    return (0);
}
